import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STColumn, STComponent, DownFileModule } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { ArchiveFileEditComponent } from './edit/edit.component';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'app-archive-file',
  templateUrl: './file.component.html',
})
export class ArchiveFileComponent implements OnInit {
  url = `/archive/dt`;
  searchSchema: SFSchema = {
    properties: {
      title: {
        type: 'string',
        title: '公文',
        ui: {
          placeholder: '编号/文号/文件标题',
        },
      },
      status: {
        type: 'string',
        title: '状态',
        enum: [
          { label: '在库', value: '在库' },
          { label: '借出', value: '借出' },
        ],
        ui: {
          widget: 'radio',
          styleType: 'button',
          // change: console.log,
        },
      },
    }
  };
  @ViewChild('st') st: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'no' },
    { title: '文号', index: 'code' },
    { title: '文件标题', index: 'title' },
    { title: '来文单位', index: 'orange' },
    { title: '密级', index: 'dese' },
    { title: '状态', index: 'status' },
    // { title: '借出人', index: 'lender' },
    { title: '收文时间', index: 'receipt' },
    { title: '创建时间', type: 'date', index: 'createAt' },
    {
      title: '操作',
      fixed: 'right',
      width: '210px',
      buttons: [
        { text: '编辑', icon: 'edit', type: 'modal', modal: { component: ArchiveFileEditComponent }, click: 'reload' },
        {
          text: '删除', icon: 'delete', type: 'del', click: (record, modal, comp) => {
            this.http.post(`/archive/delete?id=${record.id}`).subscribe((res) => {
              this.message.success(`成功删除【${record.title}】`);
              this.st.reload();
            });
          }
        },

        {
          text: '下载', icon: 'download', type: 'link',
          click: (record) => {
            this.http.get(`http://localhost:8887/files/archive/${record.id}.docx`, {}, { responseType: 'blob' }).subscribe((res) => {
              const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
              var objectUrl = URL.createObjectURL(blob);
              var a = document.createElement('a');
              a.setAttribute('style', 'display:none');
              a.setAttribute('href', objectUrl);
              a.setAttribute('download', `${record.code}.docx`);
              a.click();
              URL.revokeObjectURL(objectUrl);
            })
          }
        },
      ]
    }
  ];

  constructor(private http: _HttpClient, private modal: ModalHelper, private message: NzMessageService) { }

  ngOnInit() { }

  add() {
    this.modal
      .createStatic(ArchiveFileEditComponent, { i: { id: 0 } })
      .subscribe(() => this.st.reload());
  }

}
